from django.core.paginator import Paginator, PageNotAnInteger, InvalidPage, EmptyPage
from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse
from .models import Notice


# Create your views here.
def get_notice(request):
    # 获取数据库所有的通知信息
    notices = Notice.objects.all()

    # 使用django的Paginator进行分页设计
    # 第一个参数为所有notice的对象，第二个参数为每页显示的通知数量
    paginator = Paginator(notices, 3)
    # 获取分页的总数
    page_num_all = paginator.num_pages

    # 获取url传过来的page信息，如果没有则默认赋值为1
    page_num = request.GET.get('page')
    try:
        current_page = paginator.page(page_num)
        page_num = int(page_num)
    # todo: 注意捕获异常
    except PageNotAnInteger:
        # 如果请求的页数不是整数, 返回第一页。
        current_page = paginator.page(1)
        page_num = 1
    except InvalidPage:
        # 如果请求的页数不存在, 重定向页面
        return HttpResponse('找不到页面的内容')
    except EmptyPage:
        # 如果请求的页数不在合法的页数范围内，返回结果的最后一页。
        current_page = paginator.page(page_num_all)
        page_num = page_num_all

    # 当前页面有没有下一页
    if current_page.has_next():
        next_page_num = page_num + 1
    else:
        next_page_num = page_num
    # 当前页面有没有上一页
    if current_page.has_previous():
        previous_page_num = page_num - 1
    else:
        previous_page_num = page_num

    return render(request, 'notice/templates/notice/notice.html', {
        'page_num': page_num,
        'page_num_all': page_num_all,
        'page_num_all_range': range(1, page_num_all + 1),
        'current_page': current_page,
        'next_page_num': next_page_num,
        'previous_page_num': previous_page_num
    })


def get_article(request):
    # 获取url传过来的article信息，如果没有则默认赋值为1
    global notice
    notice_id = request.GET.get('article')

    try:
        notice = Notice.objects.get(id=notice_id)
    except:
        err = '文章索引超出范围'
        return redirect(reverse('notice'), {
            'err': err
        })

    return render(request, 'notice/details.html', {
        'notice': notice
    })
